package com.OjSystem.common.security.service;

import cn.hutool.core.lang.UUID;
import com.OjSystem.common.redis.Constants.RedisConstants;
import com.OjSystem.common.redis.service.RedisService;
import com.OjSystem.common.security.domain.LoginUser;
import com.OjSystem.common.security.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {
    @Autowired
    private RedisService redisService;


    /**
     * 获取token
     * @param userId
     * @param identity
     * @return
     */
    public String createToken(Long userId,Integer identity){
        String userKey = UUID.fastUUID().toString();

        Map<String, Object> claim = new HashMap<>();
        claim.put(RedisConstants.LOGIN_USER_ID, identity);
        claim.put(RedisConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtil.genJwt(claim);

        // 将数据缓存到redis中
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        redisService.setCacheObject(RedisConstants.KEY_PREFIX + userKey, loginUser, RedisConstants.KEY_TIME_OUT, TimeUnit.MINUTES);

        return token;
    }
}
